import React, { useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Alert,
} from "react-native";
import { TextInput, Button } from "react-native-paper";
import { useRouter } from "expo-router";
import { MaterialCommunityIcons } from "@expo/vector-icons";

import { useAuth } from "@/contexts/AuthContext";

import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from "@/constants/Colors";
import { useColorScheme } from "@/hooks/useColorScheme";

export default function LoginScreen() {
  const colorScheme = useColorScheme();
  const router = useRouter();
  const tintColor = Colors[colorScheme ?? "light"].tint;

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [secureTextEntry, setSecureTextEntry] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const { login } = useAuth();

  // 邮箱格式验证正则表达式
  const validateEmail = (email: string) => {
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    return emailRegex.test(email);
  };

  const handleLogin = async () => {
    console.log(email,'email');
    
    // 表单验证
    if (!email || !password) {
      Alert.alert('错误', '请输入邮箱和密码');
      return;
    }

    // 验证邮箱格式
    if (!validateEmail(email)) {
      Alert.alert('错误', '请输入有效的邮箱地址');
      return;
    }
    
    setIsLoading(true);
    try {
      const success = await login(email, password);
      console.log('成功了',success);
      
      if (success) {
        // 登录成功后，AuthContext中的路由保护会自动重定向到主页
        console.log('成功了','success');
    
        router.push('/');
      } else {
        // 确保Alert在主线程上运行
        setTimeout(() => {
          Alert.alert('登录失败', '邮箱或密码错误，请重试');
        }, 100);
      }
    } catch (error) {
      console.log('失败了', error);
      
      // 确保Alert在主线程上运行
      setTimeout(() => {
        Alert.alert('错误', '登录过程中发生错误，请重试');
      }, 100);
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.logoContainer}>
            <Image
              source={{
                uri: "https://img.icons8.com/color/344/elderly-person.png",
              }}
              style={styles.logo}
              resizeMode='contain'
            />
            <ThemedText style={styles.appName}>日落黄昏前</ThemedText>
            <ThemedText style={styles.appSlogan}>
              连接晚年，共享美好时光
            </ThemedText>
          </View>

          <View style={styles.formContainer}>
            <TextInput
              label='邮箱'
              value={email}
              onChangeText={setEmail}
              mode='outlined'
              style={styles.input}
              autoCapitalize='none'
              keyboardType='email-address'
              left={<TextInput.Icon icon='email' color={tintColor} />}
              outlineColor='#CCCCCC'
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />

            <TextInput
              label='密码'
              value={password}
              onChangeText={setPassword}
              mode='outlined'
              style={styles.input}
              secureTextEntry={secureTextEntry}
              left={<TextInput.Icon icon='lock' color={tintColor} />}
              right={
                <TextInput.Icon
                  icon={secureTextEntry ? "eye-off" : "eye"}
                  color={tintColor}
                  onPress={() => setSecureTextEntry(!secureTextEntry)}
                />
              }
              outlineColor='#CCCCCC'
              activeOutlineColor={tintColor}
              theme={{ roundness: 10 }}
            />

            <TouchableOpacity
              style={styles.forgotPasswordContainer}
              onPress={() => console.log("忘记密码")}
            >
              <ThemedText style={styles.forgotPasswordText}>
                忘记密码？
              </ThemedText>
            </TouchableOpacity>

            <Button
              mode='contained'
              onPress={handleLogin}
              style={styles.loginButton}
              labelStyle={styles.loginButtonText}
              loading={isLoading}
              disabled={isLoading}
              theme={{ roundness: 10 }}
            >
              登录
            </Button>

            <View style={styles.registerContainer}>
              <ThemedText style={styles.registerText}>还没有账号？</ThemedText>
              <TouchableOpacity onPress={() => router.push("/auth/register")}>
                <ThemedText style={styles.registerLink}>立即注册</ThemedText>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: "center",
    padding: 20,
  },
  logoContainer: {
    alignItems: "center",
    marginBottom: 40,
  },
  logo: {
    width: 120,
    height: 120,
    marginBottom: 20,
  },
  appName: {
    fontSize: 32,
    fontWeight: "bold",
    marginBottom: 10,
  },
  appSlogan: {
    fontSize: 18,
    color: "#666",
    textAlign: "center",
  },
  formContainer: {
    width: "100%",
  },
  input: {
    marginBottom: 15,
    fontSize: 16,
    height: 60,
  },
  forgotPasswordContainer: {
    alignSelf: "flex-end",
    marginBottom: 20,
  },
  forgotPasswordText: {
    color: "#0a7ea4",
    fontSize: 16,
  },
  loginButton: {
    padding: 5,
    backgroundColor: "#0a7ea4",
  },
  loginButtonText: {
    fontSize: 18,
    fontWeight: "bold",
  },
  registerContainer: {
    flexDirection: "row",
    justifyContent: "center",
    marginTop: 20,
  },
  registerText: {
    fontSize: 16,
  },
  registerLink: {
    fontSize: 16,
    color: "#0a7ea4",
    fontWeight: "bold",
    marginLeft: 5,
  },
});
